package com.szewec.ps.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.MainActivity;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseUrl;
import com.szewec.ps.base.Constants;
import com.szewec.ps.databinding.ActivityLoginBinding;
import com.szewec.ps.model.response.ResponseData;
import com.szewec.ps.model.user.UserModel;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.tabbar.HomePageActivity;
import com.szewec.ps.util.ListUtil;
import com.szewec.ps.util.LogUtil;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.HashMap;

import butterknife.ButterKnife;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private ActivityLoginBinding binding;
    private String username;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        ButterKnife.bind(this);

        initListener();
    }

    private void initListener(){
        binding.ivClear1.setOnClickListener(view -> binding.username.setText(""));
        binding.ivClear2.setOnClickListener(view -> binding.password.setText(""));
        binding.username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().length() > 0){
                    binding.ivClear1.setVisibility(View.VISIBLE);
                }else {
                    binding.ivClear1.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                username = editable.toString();
            }
        });
        binding.password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().length() > 0){
                    binding.ivClear2.setVisibility(View.VISIBLE);
                }else {
                    binding.ivClear2.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                password = editable.toString();
            }
        });

        binding.loginBtn.setOnClickListener(view -> doLogin());
    }

    private void doLogin(){
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)){
            HashMap<String,String> param = new HashMap<>();
            param.put(PreferincesContext.USERNAME,username);
            param.put(PreferincesContext.PASSWORD,password);
            OkHttp.postByForm(BaseUrl.platform + "/account/appLogin", param, new OkHttp.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    LogUtil.i(TAG,"登陆结果:"+result);
                    JSONObject jsonObject = JSON.parseObject(result);
                    if (jsonObject.get("code").equals("SUCCESS")){//登陆成功
                        //登录成功保存用户名和密码
                        SharedPreferencesUtil.putData(PreferincesContext.USERNAME, username);
                        SharedPreferencesUtil.putData(PreferincesContext.PASSWORD, password);
                        String token = (String) jsonObject.get("result");
                        //存储token
                        SharedPreferencesUtil.putData(PreferincesContext.TOKEN,token);
                        //解析token获取用户信息
                        handleToken(token);
                    }else {
                        BamToast.showText(LoginActivity.this,jsonObject.get("message").toString());
                    }
                }
            });
        }else {
            BamToast.showText(this,"手机号或密码不能为空");
        }
    }

    private void handleToken(String token){
        OkHttp.getWithoutBaseUrl(BaseUrl.platform + "/account/accountRestService/getToken?clientToken=" + token, new OkHttp.MyCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(TAG,"token解析结果:"+result);
                if (StringUtils.isNotEmpty(result)){
                    //存储companyId,根据userId获取用户的中文名字
                    JSONObject jsonObject = JSON.parseObject(result);
                    String companyId = (String) jsonObject.get("companyId");
                    SharedPreferencesUtil.putData(PreferincesContext.COMPANY_ID,companyId);
                    String userId = (String) jsonObject.get("userId");
                    SharedPreferencesUtil.putData(PreferincesContext.USER_ID,userId);
                    queryAppList(companyId,userId);
//                    queryUserInfo(userId);
                }
            }
        });
    }

    /**
     * 校验是否拥有应用权限
     */
    private void queryAppList(String companyId,String userId){
        OkHttp.get("/tpms-plan-service/api/roles-management/check?userId="+userId+"&tenantId="+companyId+"&appId="+BaseUrl.APP_ID, null,null,new OkHttp.MyCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(TAG,"是否拥有应用权限:"+result);
                Boolean pass = JSON.parseObject(result).getBoolean("data");
                if (pass){
                    queryUserInfo(userId);
                }else {
                    showFailed();
                }
            }
        });
    }

    private void queryUserInfo(String userId){
        OkHttp.getWithoutBaseUrl(BaseUrl.platform + "/unit/userRestService/get?id=" + userId, new OkHttp.MyCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(TAG,"用户信息:"+result);
                if (StringUtils.isNotEmpty(result)){
                    SharedPreferencesUtil.putData(PreferincesContext.USER_INFO,result);
                    UserModel userModel = JSON.parseObject(result,UserModel.class);
                    if (userModel != null){
                        SharedPreferencesUtil.putData(PreferincesContext.USER_COMPANY_NAME,userModel.getCompanyName());
                        SharedPreferencesUtil.putData(PreferincesContext.USER_SHOW_NAME,userModel.getName());

                    }
                    //去选项目
                    Intent intent = new Intent(LoginActivity.this,SelectProjectAndStageActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra(Constants.EXTRA_KEY.LOGIN,true);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    private void showFailed(){
        runOnUiThread(() -> BamToast.showText(LoginActivity.this,"当前账号没有权限,请联系系统管理员获取",3000));
    }
    //监听返回键
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
                toast.setText("再按一次返回键退出应用");
                toast.show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                //退出应用
//                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
